package server.handler;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import org.json.JSONArray;
import org.json.JSONObject;
import server.database.RegistrationDatabase;
import server.util.MD5Util;
import server.util.SessionUtil;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;

public class Handler {
    private static Integer maxDataLen = 1024;
    public static SessionUtil sessionUtil = new SessionUtil();

    public static String getRequestData(HttpExchange exchange) throws IOException {
        InputStream inputStream = exchange.getRequestBody();
        if(inputStream.available() > maxDataLen){
            throw new IOException("Maximum message length limit exceeded");
        }
        ByteArrayOutputStream result = new ByteArrayOutputStream();
        byte[] buffer = new byte[maxDataLen];
        for (int l; (l = inputStream.read(buffer)) != -1; ) {
            result.write(buffer, 0, l);
        }
        return result.toString("UTF-8");
    }

    public static boolean authentication(HttpExchange exchange){
        Headers headers = exchange.getRequestHeaders();
        if(!headers.containsKey("session")){
            return false;
        }
        String session = headers.get("session").get(0);
        return isLogin(session);
    }

    public static String getUserName(HttpExchange exchange){
        Headers headers = exchange.getRequestHeaders();
        String session = headers.get("session").get(0);
        return getLoginUserName(session);
    }
    public static void errorHandler(HttpExchange exchange, Exception e) throws IOException {
        OutputStream outputStream = exchange.getResponseBody();
        String message = e.getMessage();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("message", message);
        String response = jsonObject.toString();
        exchange.getResponseHeaders().add("content-Type", "application/json");
        exchange.sendResponseHeaders(500, response.length());
        outputStream.write(response.getBytes());
        outputStream.flush();
        outputStream.close();
        System.out.println(e.getMessage());
    }

    public static void errorHandler(HttpExchange exchange, String e) throws IOException {
        OutputStream outputStream = exchange.getResponseBody();
        String message = e;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("message", message);
        String response = jsonObject.toString();
        exchange.getResponseHeaders().add("content-Type", "application/json");
        exchange.sendResponseHeaders(500, response.length());
        outputStream.write(response.getBytes());
        outputStream.flush();
        outputStream.close();
        System.out.println(e);
    }


    public static void sendResponse(HttpExchange exchange, String message) throws IOException {
        OutputStream outputStream = exchange.getResponseBody();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("message", message);
        String response = jsonObject.toString();
        exchange.getResponseHeaders().add("content-Type", "application/json");
        exchange.sendResponseHeaders(200, response.length());
        outputStream.write(response.getBytes());
        outputStream.flush();
        outputStream.close();
    }

    public static void sendResponse(HttpExchange exchange, JSONObject jsonObject) throws IOException {
        OutputStream outputStream = exchange.getResponseBody();
        String response = jsonObject.toString();
        exchange.getResponseHeaders().add("content-Type", "application/json");
        exchange.sendResponseHeaders(200, response.length());
        outputStream.write(response.getBytes());
        outputStream.flush();
        outputStream.close();
    }

    public static void sendResponse(HttpExchange exchange, JSONArray jsonArray) throws IOException {
        OutputStream outputStream = exchange.getResponseBody();
        String response = jsonArray.toString();
        exchange.getResponseHeaders().add("content-Type", "application/json");
        exchange.sendResponseHeaders(200, response.length());
        outputStream.write(response.getBytes());
        outputStream.flush();
        outputStream.close();
    }

    public static LocalDateTime localDateTimeToEpochMilli(String dateText){
        OffsetDateTime odt = OffsetDateTime.parse(dateText);
        return odt.toLocalDateTime();
    }

    public  static String getSession(String userName) throws Exception {
        return MD5Util.encryMD5(userName);
    }
    public static void insertSession(String session, String userName){
        sessionUtil.sessionToUserName.put(session, userName);
    }
    public  static void removeSession(String session){
        sessionUtil.sessionToUserName.remove(session);
    }
    public  static boolean isLogin(String session){
        return sessionUtil.sessionToUserName.containsKey(session);
    }
    public  static String getLoginUserName(String session){
        if(!sessionUtil.sessionToUserName.containsKey(session)){
            return null;
        }
        return sessionUtil.sessionToUserName.get(session);
    }
}
